package com.example.hs.Controller;

import com.example.hs.Pojo.Recycler;
import com.example.hs.Service.RecyclerService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/recycler")
public class RecyclerController {
    @Autowired
    private RecyclerService recyclerService;

    @PostMapping("/register")
    public ResponseEntity<Recycler> register(@RequestBody Recycler recycler) {

        return ResponseEntity.ok(recyclerService.register(recycler));
    }

    @PostMapping("/login")
    public ResponseEntity<Recycler> login(@RequestBody Recycler recycler, HttpSession session) {
        if (recycler.getNum() != null && recycler.getPassword() != null) {
            return ResponseEntity.ok(recyclerService.login(recycler.getNum(), recycler.getPassword(), session));
        }
        return ResponseEntity.badRequest().build();
    }

    @GetMapping("/profile")
    public ResponseEntity<Recycler> getProfile(HttpSession session) {
        if (session.getAttribute("recycler") == null){
            return ResponseEntity.notFound().build();
        }else {
            return ResponseEntity.ok(recyclerService.getProfile(session)); // 从Session中获取用户信息
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<Recycler>> getAllRecyclers() {
        return ResponseEntity.ok(recyclerService.getAllRecyclers());
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout(HttpSession session) {
        recyclerService.logout(session);
        return ResponseEntity.ok().build();
    }
    @PostMapping("/update")
    public ResponseEntity<Recycler> updateRecycler(HttpSession session, @RequestBody Recycler updatedRecycler) {
        Recycler recycler = recyclerService.updateRecycler(session, updatedRecycler);
        if (recycler != null) {
            return ResponseEntity.ok(recycler);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
